package com.a918.controller;

import com.a918.dto.TableResponse;
import com.a918.entity.*;
import com.a918.service.UserService;
import com.a918.util.IPGet;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
public class UserManageController {


    private UserService userService;

    @Autowired
    public UserManageController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/userinfo")
    public String userinfo(HttpServletRequest request, Model model) {
        userService.insertlog("用户信息","userinfo",(String) request.getSession().getAttribute("username"), IPGet.getIp(request));

        String username = (String) request.getSession().getAttribute("username");
        User user = userService.getUserByUsername(username);
        model.addAttribute("user",user);
        return "back/userinfo";
    }

    //注册审核
    @GetMapping("/register_check_list")
    public String register_check_list() {
        return "back/register_check_list";
    }

    //待审核列表
    @RequestMapping(value = "/getUserList_check")
    @ResponseBody
    public Object getmemOthList(@RequestParam Map<String, String> paramMap) {
        PageInfo<User> pageInfo_user=userService.findUserList_check(paramMap);
        return new TableResponse(0,"查询成功", pageInfo_user.getList(),pageInfo_user.getTotal());
    }

    //审核
    @RequestMapping("/registercheck/{status}")
    @ResponseBody
    public String registercheck(@PathVariable(value="status",required=true)String status, HttpServletRequest request) {
        Integer userid = (Integer) request.getSession().getAttribute("id");
        Integer id = Integer.valueOf(request.getParameter("id"));
        if (status.equals("tongguo")){
            String role_list = request.getParameter("role");
            List<String> roleid_list = Arrays.asList(role_list.split(","));

            User user =new User();
            user.setId(id);
            user.setCheckstatus(2);
            userService.updateUserCheckstatus(user);

            for(String roleid:roleid_list ){
                User2role user2role = new User2role();
                user2role.setRoleid(Integer.valueOf(roleid));
                user2role.setUserid(id);
                user2role.setCreattime(new Date());
                userService.insertUser2Role(user2role);
            }

        }else if(status.equals("butongguo")){
            String shenheyijian = request.getParameter("shenheyijian");

            User user =new User();
            user.setId(id);
            user.setCheckstatus(-1);
            userService.updateUserCheckstatus(user);

            FrontFcCheck frontFcCheck = new FrontFcCheck();
            frontFcCheck.setOpinion(shenheyijian);
            frontFcCheck.setCheckerid(userid);
            frontFcCheck.setCreattime(new Date());
            frontFcCheck.setCheckid(id);
            frontFcCheck.setType("register");
            userService.insertShenheyijian(frontFcCheck);
        }

        return "success";
    }

    @RequestMapping("/getRoleList")
    @ResponseBody
    public Map<String, Object> getRoleList(){
        List<Role> roleList = userService.getRoleList();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("roleList", roleList);
        return map;

    }
    @GetMapping("/permission/{type}")
    public String permission(@PathVariable(value="type",required=true)String type) {
        switch(type){
            //权限列表
            case "plist":
                return "back/permissionlist";
            //角色管理
            case "role":
                return "back/rolemanage";
            default:
                return null;
        }
    }

    @PostMapping("/permissionlist")
    @ResponseBody
    public Object permissionlist(@RequestParam Map<String, String> paramMap){
        int pno=Integer.parseInt(paramMap.get("page"));
        int pageSize=Integer.parseInt(paramMap.get("limit"));
        PageHelper.startPage(pno, pageSize);
        List<Permission> permissionList = userService.getPermissionList();
        PageInfo<Permission> pageInfo = new PageInfo<Permission>(permissionList);
        return new TableResponse(0,"查询成功", pageInfo.getList(),pageInfo.getTotal());
    }

    @PostMapping("/roleList")
    @ResponseBody
    public Object roleList(HttpServletRequest request, @RequestParam Map<String, String> paramMap){
        int pno=Integer.parseInt(paramMap.get("page"));
        int pageSize=Integer.parseInt(paramMap.get("limit"));
        PageHelper.startPage(pno, pageSize);
        List<Role> roleList = userService.getRoleList();
        PageInfo<Role> pageInfo  = new PageInfo<Role>(roleList);
        return new TableResponse(0,"查询成功", pageInfo.getList(),pageInfo.getTotal());
    }

    @PostMapping("/addRole")
    @ResponseBody
    public String addRole(Role role){
        try{
            userService.insertRole(role);
            return "success";
        }catch (Exception e){
            System.out.println(e);
            return "error";
        }

    }

    @PostMapping("/delRole")
    @ResponseBody
    public String delRole(String id){
        try{
            userService.delRole(id);
            return "success";
        }catch (Exception e){
            System.out.println(e);
            return "error";
        }
    }

    @PostMapping("/getrole2per")
    @ResponseBody
    public JSONObject getrole2per(String id ){
        List<Map<String, Object>> perlist = userService.getPermissionByRole(Integer.valueOf(id));
        Map<String, Object> res = new HashMap<>();
        res.put("res",perlist);
        return new JSONObject(res);
    }


    @PostMapping("/role2perManage")
    @ResponseBody
    public String role2perManage(HttpServletRequest request){
        try{
            String type = request.getParameter("type");
            Integer roleid = Integer.valueOf(request.getParameter("roleid"));
            Integer perid = Integer.valueOf(request.getParameter("perid"));
            userService.roleManage(type,roleid,perid);
            return "success";
        }catch (Exception e){
            System.out.println(e);
            return "error";
        }
    }

    @PostMapping("/getuser2role")
    @ResponseBody
    public JSONObject getuser2role(String id ){
        List<Map<String, Object>> rolelist = userService.getRoleByUser(Integer.valueOf(id));
        Map<String, Object> res = new HashMap<>();
        res.put("res",rolelist);
        return new JSONObject(res);
    }



    @PostMapping("/user2roleManage")
    @ResponseBody
    public String user2roleManage(HttpServletRequest request){
        try{
            String type = request.getParameter("type");
            Integer roleid = Integer.valueOf(request.getParameter("roleid"));
            Integer userid = Integer.valueOf(request.getParameter("userid"));
            userService.user2roleManage(type,roleid,userid);
            return "success";
        }catch (Exception e){
            System.out.println(e);
            return "error";
        }
    }


    @GetMapping("/usermanage/{type}")
    public String usermanage(@PathVariable(value="type",required=true)String type) {
        switch(type){
            //注册审核
            case "check":
                return null;
            //会员管理
            case "list":
                return "back/usermanage";
            default:
                return null;
        }
    }

    @PostMapping("/userlist")
    @ResponseBody
    public Object userlist(int page, int limit,@RequestParam Map<String, String> paramMap){
        PageHelper.startPage(page, limit);
        PageInfo<User> pageInfo  = new PageInfo<User>(userService.getUserList(paramMap));
        return new TableResponse(0,"查询成功", pageInfo.getList(),pageInfo.getTotal());
    }


    @PostMapping("/deluser")
    @ResponseBody
    public String deluser(String id){
        try{
            userService.delUser(Integer.valueOf(id));
            return "success";
        }catch (Exception e){
            System.out.println(e);
            return "error";
        }
    }

    @PostMapping("/resetPwd")
    @ResponseBody
    public String resetPwd(String id,String pwd){
        User user = userService.getUserById(Integer.valueOf(id));
        user.setPassword(pwd);
        userService.updateUser(user);
        return "success";

    }


    @GetMapping("/sqlbf")
    public String sqlbf(HttpServletRequest request) {
        userService.insertlog("数据库备份","sqlbf",(String) request.getSession().getAttribute("username"), IPGet.getIp(request));
        return "back/sqlbf";
    }

    @PostMapping("/dbbackup")
    public String dbbackup() {
        String filePath="D:\\教师成长档案管理系统\\";
        /*String fileName="批量上传模板.xlsx";*/
        String dbName="teacher";
        try {
            Process process = Runtime.getRuntime().exec(
                    "cmd  /c  mysqldump -u root -proot " + dbName + " > "
                            + filePath + "/" + dbName+new java.util.Date().getTime()
                            + ".sql");
            //备份的数据库名字为teacher，数据库连接和密码均为root
            System.out.println("success!!!");
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }



}